<?php

namespace app\models;

use yii\base\Model;

/**
 * ActiveMQ消息队列接口
 * Class ActiveMqApi
 * @package app\models
 */
class ActiveMqApi extends Model
{
    /**
     * @var string 目标
     */
    private $dest;
    /**
     * @var \Stomp 消息队列Stomp连接实例
     */
    private $stomp;

    /**
     * ActiveMQApi constructor.
     * @param string $dest 队列目标
     * @inheritdoc
     */
    public function __construct($dest)
    {
        $this->dest = $dest;
        if (YII_DEBUG) {
            $this->dest .= YII_ENV;
        }
        parent::__construct([]);
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        $url = System::getConfig('mq_url');
        $this->stomp = new \Stomp($url);
        $this->stomp->setReadTimeout(1);
        parent::init();
    }

    /**
     * 关闭队列
     */
    public function close()
    {
        unset($this->stomp);
    }

    /**
     * 订阅
     */
    public function subscribe() {
        $this->stomp->subscribe($this->dest);
    }

    /**
     * 取消订阅
     */
    public function unsubscribe()
    {
        $this->stomp->unsubscribe($this->dest);
    }

    /**
     * 返回是否有可读的帧
     * @return boolean
     */
    public function hasFrame()
    {
        return $this->stomp->hasFrame();
    }

    /**
     * 返回队列帧
     * @return \stdClass
     */
    public function readFrame()
    {
        return $this->stomp->readFrame();
    }

    /**
     * 开始事务
     * @param $id
     * @return mixed
     */
    public function begin($id)
    {
        return $this->stomp->begin($id);
    }

    /**
     * 提交事物
     * @param $id
     * @return mixed
     */
    public function commit($id)
    {
        return $this->stomp->commit($id);
    }

    /**
     * 通知已处理帧
     * @param $frame
     * @return boolean
     */
    public function ack($frame)
    {
        return $this->stomp->ack($frame);
    }

    /**
     * 发送数据
     * @param array $data 数据
     * @param integer $priority 优先级 0-9
     */
    public function send($data, $priority = 4)
    {
        $this->stomp->send($this->dest, json_encode($data), [
            'priority' => $priority,
        ]);
    }
}
